package me.denger.database2Word;

import me.denger.database2Word.bean.Table;
import me.denger.database2Word.config.ConfigBean;
import me.denger.database2Word.config.ConfigService;
import me.denger.database2Word.inteface.DatabaseInterFace;
import me.denger.database2Word.service.DatabaseImp4Mysql;
import me.denger.database2Word.service.DatabaseImp4Oracle;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class App {

    public static void main(String[] args) {

        //读取配置
        ConfigBean configBean = ConfigService.readOut();
        // ConfigBean configBean = ConfigService.read();

        String gitAddress = "gitee.com/denger/Database2Word";

        if (null == configBean.getFileName()) {
            ConfigBean read = ConfigService.read();
            configBean.setFileName(read.getFileName());
        }

        JFrame jf = new JFrame("Database2Word");
        jf.setSize(500, 200);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);

        GridBagLayout gridBag = new GridBagLayout();
        GridBagConstraints c = null; // 约束

        JPanel panel = new JPanel(gridBag);

        JLabel urlLab = new JLabel("数据库URL");
        c = new GridBagConstraints();
        gridBag.addLayoutComponent(urlLab, c);
        panel.add(urlLab);
        final JTextField urlText = new JTextField(15);
        urlText.setText(configBean.getUrl());
        c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(urlText, c);
        panel.add(urlText);

        JLabel userLab = new JLabel("用户名");
        c = new GridBagConstraints();
        gridBag.addLayoutComponent(userLab, c);
        panel.add(userLab);
        final JTextField userText = new JTextField(15);
        userText.setText(configBean.getUserName());
        c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(userText, c);
        panel.add(userText);

        JLabel passwdLab = new JLabel("密码");
        c = new GridBagConstraints();
        gridBag.addLayoutComponent(passwdLab, c);
        panel.add(passwdLab);
        final JPasswordField passwordField = new JPasswordField(15);
        passwordField.setText(configBean.getPassword());
        c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(passwordField, c);
        panel.add(passwordField);

        JLabel tableNamePrefixLab = new JLabel("表的前缀(不含*)");
        c = new GridBagConstraints();
        gridBag.addLayoutComponent(tableNamePrefixLab, c);
        panel.add(tableNamePrefixLab);
        final JTextField tableNamePrefixText = new JTextField(15);
        c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(tableNamePrefixText, c);
        panel.add(tableNamePrefixText);

        final JButton enterBtn = new JButton("导出文档(enter)");
        c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(enterBtn, c);
        panel.add(enterBtn);

        // 项目地址

        final JLabel msgLab = new JLabel("点击复制GIT项目地址：" + gitAddress);
        c = new GridBagConstraints();
        c.gridheight = 2;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        gridBag.addLayoutComponent(msgLab, c);
        panel.add(msgLab);

        msgLab.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                //忽略
            }

            @Override
            public void mousePressed(MouseEvent e) {
                //忽略
            }

            @Override
            public void mouseExited(MouseEvent e) {
                //忽略
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                //忽略
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable tText = new StringSelection(gitAddress);
                clip.setContents(tText, null);
                JOptionPane.showConfirmDialog(msgLab, "已复制到剪切板", "结果", JOptionPane.CLOSED_OPTION);
            }
        });

        jf.setContentPane(panel);
        // jf.pack();
        jf.setLocationRelativeTo(null);
        jf.setVisible(true);

        // 添加处理事件
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String driver;
                String url = urlText.getText();
                String userName = userText.getText();
                String password = new String(passwordField.getPassword());
                String tableNamePrefix = tableNamePrefixText.getText();

                try {
                    DatabaseInterFace databaseInterFace;
                    if (url.isEmpty()) {
                        showErrMsg(enterBtn, "请输入oracle或者mysql的完整url");
                        return;

                    } else if (url.startsWith("jdbc:oracle")) {
                        driver = "oracle.jdbc.driver.OracleDriver";
                        databaseInterFace = new DatabaseImp4Oracle(driver, url, userName,
                                password);
                    } else if (url.startsWith("jdbc:mysql")) {
                        driver = "com.mysql.cj.jdbc.Driver";
                        String jdbcGetSqlCommentPara = "useInformationSchema=true";
                        if (url.indexOf(jdbcGetSqlCommentPara) < 0) {
                            if (url.indexOf('?') < 0) {
                                url = url + '?' + jdbcGetSqlCommentPara;
                            } else {
                                url = url + '&' + jdbcGetSqlCommentPara;
                            }
                        }
                        databaseInterFace = new DatabaseImp4Mysql(driver, url, userName, password);
                    } else {
                        showErrMsg(enterBtn, "实在抱歉，暂时仅支持oracle和mysql的url，如果有需要请联系请到Git进行反馈");
                        return;
                    }

                    long timeStart = System.currentTimeMillis();
                    List<Table> allTableAndColumn;
                    if (tableNamePrefix != null && tableNamePrefix.length() > 0) {
                        allTableAndColumn = databaseInterFace.getTables(tableNamePrefix + "%");
                    } else {
                        allTableAndColumn = databaseInterFace.getTables(null);
                    }
                    configBean.setDriver(driver);
                    configBean.setUrl(url);
                    configBean.setUserName(userName);
                    configBean.setPassword(password);

                    //保存配置文件
                    ConfigService.writeOut(configBean);

                    int tableNum = FileUtil.write2Word(configBean.getFileName(), allTableAndColumn);

                    long timeEnd = System.currentTimeMillis() - timeStart;
                    StringBuilder resultStr = new StringBuilder();
                    resultStr.append("导出成功，");
                    resultStr.append(tableNum);
                    resultStr.append("张表，耗时");
                    if (timeEnd < TimeUnit.SECONDS.toMillis(1)) {
                        resultStr.append(timeEnd).append("毫");
                    } else {
                        double v = timeEnd / 1000.0;
                        resultStr.append(v);
                    }
                    resultStr.append("秒");
                    resultStr.append(System.getProperty("line.separator"));
                    resultStr.append("文件路径为：");
                    resultStr.append(configBean.getFileName());
                    String formatText = resultStr.toString();

                    msgLab.setText(formatText);
                    int showConfirmDialogNum = JOptionPane.showConfirmDialog(enterBtn, formatText + "是否现在打开文件？", "结果",
                            JOptionPane.YES_NO_OPTION);
                    if (showConfirmDialogNum == 0) {
                        // 打开导出的文件
                        Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler " + configBean.getFileName());
                    }
                } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                    showErrMsg(enterBtn, "找不到jdbc驱动，请到Git进行反馈");
                } catch (SQLException e1) {
                    e1.printStackTrace();
                    showErrMsg(enterBtn, "连接失败");
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                    showErrMsg(enterBtn, e1.getMessage());
                } catch (Exception e1) {
                    e1.printStackTrace();
                    showErrMsg(enterBtn, "导出数据出现异常，请到Git进行反馈");
                }
            }

            private void showErrMsg(final JButton testBtn, String msg) {
                JOptionPane.showMessageDialog(testBtn, msg, "结果", JOptionPane.ERROR_MESSAGE);
            }
        };

        // 绑定回车键
        enterBtn.registerKeyboardAction(actionListener, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        enterBtn.addActionListener(actionListener);
    }
}